home *** CD-ROM | disk | FTP | other *** search
/ Compendium Deluxe 2 / LSD and 17bit Compendium Deluxe - Volume II.iso / a / prog / cprog / programminginc.lha / ProgrammingInC.txt
Encoding:
Text File  |  1994-09-29  |  59.6 KB  |  1,877 lines

  1.                PROGRAMMING IN C: A TUTORIAL
  2.  
  3. By BRIAN W. KERNIGHAN.
  4.  
  5.  
  6. 1.  Introduction.
  7.  
  8.      C is a computer language available on the GCOS and UNIX
  9. operating  systems  at Murray Hill and (in preliminary form)
  10. on OS/360 at  Holmdel.   C  lets  you  write  your  programs
  11. clearly  and  simply _ it has decent control flow facilities
  12. so your code can be read straight  down  the  page,  without
  13. labels  or  GOTO's;  it  lets you write code that is compact
  14. without being too cryptic; it encourages modularity and good
  15. program  organization; and it provides good data-structuring
  16. facilities.
  17.  
  18.      This memorandum is a tutorial to  make  learning  C  as
  19. painless  as  possible.   The first part concentrates on the
  20. central features of C; the second part discusses those parts
  21. of  the  language which are useful (usually for getting more
  22. efficient and smaller code) but which are not necessary  for
  23. the  new user.  This is "not" a reference manual.  Details and
  24. special cases will be skipped  ruthlessly,  and  no  attempt
  25. will  be made to cover every language feature.  The order of
  26. presentation is hopefully pedagogical  instead  of  logical.
  27. Users  who  would  like  the full story should consult the 'C
  28. Reference Manual' by D. M. Ritchie [1], which should be  read
  29. for details anyway.  Runtime support is described in [2] and
  30. [3]; you will have to read one of these to learn how to com-
  31. pile and run a C program.
  32.  
  33.      We will assume that you are familiar with the mysteries
  34. of creating files, text editing, and the like in the operat-
  35. ing system you run on, and that you have programmed in  some
  36. language before.
  37.  
  38.  
  39. 2. A Simple C Program
  40.  
  41.  
  42.      main( ) {
  43.              printf("hello, world");
  44.      }
  45.  
  46.  
  47.      A C program consists of one or  more  functions,  which
  48. are  similar  to  the functions and subroutines of a Fortran
  49. program or the procedures of PL/I, and perhaps some external
  50. data  definitions.  main is such a function, and in fact all
  51. C programs must have  a  main.   Execution  of  the  program
  52. begins  at  the  first statement of main.  main will usually
  53. invoke other functions to perform its job, some coming  from
  54. the same program, and others from libraries.
  55.  
  56.      One method of communicating data between  functions  is
  57. by  arguments.   The parentheses following the function name
  58. surround the argument list; here main is a  function  of  no
  59. arguments,  indicated by ( ).  The {} enclose the statements
  60. of the function.  Individual statements end with a semicolon
  61. but are otherwise free-format.
  62.  
  63.      printf is a library  function  which  will  format  and
  64. print  output on the terminal (unless some other destination
  65. is specified).  In this  case it prints
  66.  
  67.      hello, world
  68.  
  69. A function is invoked by naming it, followed by  a  list  of
  70. arguments  in parentheses.  There is no CALL statement as in
  71. Fortran or PL/I.
  72.  
  73. 3. A Working C Program; Variables; Types and Type Declarations
  74.  
  75.      Here's a bigger program that adds  three  integers  and
  76. prints their sum.
  77.  
  78.      main( ) {
  79.              int a, b, c, sum;
  80.              a = 1;  b = 2;  c = 3;
  81.              sum = a + b + c;
  82.              printf("sum is %d", sum);
  83.      }
  84.  
  85.  
  86.      Arithmetic and the assignment statements are  much  the
  87. same as in Fortran (except for the semicolons) or PL/I.  The
  88. format of C programs is quite  free.   We  can  put  several
  89. statements on a line if we want, or we can split a statement
  90. among several lines if it seems desirable. The split may  be
  91. between  any  of  the operators or variables, but NOT in the
  92. middle of a name or operator.  As a matter of style, spaces,
  93. tabs,  and  newlines should be used freely to enhance reada-
  94. bility.
  95.  
  96.      C has four fundamental types of variables:
  97.  
  98.  int     integer (PDP-11: 16 bits; H6070: 36 bits; IBM360: 32 bits)
  99.  char    one byte character (PDP-11, IBM360: 8 bits; H6070: 9 bits)
  100.  float   single-precision floating point
  101.  double  double-precision floating point
  102.  
  103. There are also arrays and structures of these  basic  types,
  104. pointers  to  them  and  functions  that return them, all of
  105. which we will meet shortly.
  106.  
  107.      All variables in a C program must be declared, although
  108. this  can sometimes be done implicitly by context.  Declara-
  109. tions must precede executable statements.  The declaration
  110.  
  111.      int a, b, c, sum;
  112.  
  113. declares a, b, c, and sum to be integers.
  114.  
  115.      Variable names have one  to  eight  characters,  chosen
  116. from  A-Z,  a-z,  0-9,  and  _,  and start with a non-digit.
  117. Stylistically, it's much better to use only  a  single  case
  118. and  give  functions  and  external variables names that are
  119. unique in the first six characters.  (Function and  external
  120. variable names are used by various assemblers, some of which
  121. are limited in the size and case  of  identifiers  they  can
  122. handle.)  Furthermore,  keywords  and  library functions may
  123. only be recognized in one case.
  124.  
  125. 4. Constants
  126.  
  127.      We have already seen decimal integer constants  in  the
  128. previous  example  _ 1, 2, and 3.  Since C is often used for
  129. system programming and bit-manipulation, octal  numbers  are
  130. an  important  part  of the language.  In C, any number that
  131. begins with 0 (zero!) is an octal integer (and  hence  can't
  132. have any 8's or 9's in it).  Thus 0777 is an octal constant,
  133. with decimal value 511.
  134.  
  135.      A ``character'' is one  byte  (an  inherently  machine-
  136. dependent concept).  Most often this is expressed as a character
  137. constant, which is one character  enclosed  in  single
  138. quotes.   However,  it  may  be  any quantity that fits in a
  139. byte, as in flags below:
  140.  
  141.      char quest, newline, flags;
  142.      quest = '?';
  143.      newline = '\n';
  144.      flags = 077;
  145.  
  146.      The sequence `\n' is C notation for  ``newline  charac-
  147. ter'', which, when printed, skips the terminal to the begin-
  148. ning of the next line.  Notice that `\n' represents  only  a
  149. single  character.  There are several other ``escapes'' like
  150. `\n'  for representing hard-to-get or invisible  characters,
  151. such  as  `\t'  for tab, `\b' for backspace, `\0' for end of
  152. file, and `\\' for the backslash itself.
  153.  
  154.      float and double constants are discussed in section 26.
  155.  
  156. 5. Simple I/O _ getchar, putchar, printf
  157.  
  158.  
  159.      main( ) {
  160.              char c;
  161.              c = getchar( );
  162.              putchar(c);
  163.      }
  164.  
  165.  
  166.      getchar and putchar are the basic I/O library functions
  167. in C.  getchar fetches one character from the standard input
  168. (usually the terminal) each time it is called,  and  returns
  169. that  character  as  the  value  of  the  function.  When it
  170. reaches the end of whatever file it is  reading,  thereafter
  171. it  returns  the  character  represented by `\0' (ascii NUL,
  172. which has value zero).  We will see how  to  use  this  very
  173. shortly.
  174.  
  175.      putchar puts one character out on the  standard  output
  176. (usually  the terminal) each time it is called.  So the pro-
  177. gram above reads one character and writes it back  out.   By
  178. itself,  this isn't very interesting, but observe that if we
  179. put a loop around this, and add a test for end of  file,  we
  180. have a complete program for copying one file to another.
  181.  
  182.      printf is a more  complicated  function  for  producing
  183. formatted  output.  We will talk about only the simplest use
  184. of it.  Basically, printf uses its first argument as format-
  185. ting  information, and any successive arguments as variables
  186. to be output.  Thus
  187.  
  188.      printf ("hello, world\n");
  189.  
  190. is the simplest use  _  the  string  ``hello,  world\n''  is
  191. printed  out.   No  formatting information, no variables, so
  192. the string is dumped out verbatim.  The newline is necessary
  193. to put this out on a line by itself.  (The construction
  194.  
  195.      "hello, world\n"
  196.  
  197. is really an array of chars.  More about this shortly.)
  198.  
  199.      More complicated, if sum is 6,
  200.  
  201.      printf ("sum is %d\n", sum);
  202.  
  203. prints
  204.  
  205.      sum is 6
  206.  
  207. Within the first argument of printf, the  characters  ``%d''
  208. signify that the next argument in the argument list is to be
  209. printed as a base 10 number.
  210.  
  211.      Other useful formatting commands are  ``%c''  to  print
  212. out  a  single  character,  ``%s''  to  print  out an entire
  213. string, and ``%o'' to print a number  as  octal  instead  of
  214. decimal (no leading zero).  For example,
  215.  
  216.      n = 511;
  217.      printf ("What is the value of %d in octal?", n);
  218.      printf ("  %s! %d decimal is %o octal\n", "Right", n, n);
  219.  
  220. prints
  221.  
  222.      What is the value of 511 in octal?  Right! 511  decimal
  223.      is 777 octal
  224.  
  225. Notice that there is no newline at the end of the first out-
  226. put  line.   Successive calls to printf (and/or putchar, for
  227. that matter) simply put out  characters.   No  newlines  are
  228. printed unless you ask for them.  Similarly, on input, char-
  229. acters are read one at a time as you  ask  for  them.   Each
  230. line is generally terminated by a newline (\n), but there is
  231. otherwise no concept of record.
  232.  
  233. 6. If; relational operators; compound statements
  234.  
  235.      The basic conditional-testing statement in C is the  if
  236. statement:
  237.  
  238.      c = getchar( );
  239.      if( c == '?' )
  240.              printf("why did you type a question mark?\n");
  241.  
  242. The simplest form of if is
  243.  
  244.      if (expression) statement
  245.  
  246.  
  247.      The condition to be tested is any  expression  enclosed
  248. in parentheses.  It is followed by a statement.  The expres-
  249. sion is evaluated, and if its value is non-zero, the  state-
  250. ment  is  executed.   There's an optional else clause, to be
  251. described soon.
  252.  
  253.      The character sequence `=='  is one of  the  relational
  254. operators in C; here is the complete set:
  255.  
  256.      ==      equal to (.EQ. to Fortraners)
  257.      !=      not equal to
  258.      >       greater than
  259.      <       less than
  260.      >=      greater than or equal to
  261.      <=      less than or equal to
  262.  
  263.  
  264.      The value of ``expression relation expression'' is 1 if
  265. the relation is true, and 0 if false.  Don't forget that the
  266. equality test is `=='; a single `='  causes  an  assignment,
  267. not a test, and invariably leads to disaster.
  268.  
  269.      Tests can be combined with the  operators  `&&'  (AND),
  270. `||'  (OR), and `!' (NOT).  For example, we can test whether
  271. a character is blank or tab or newline with
  272.  
  273.      if( c==' ' || c=='\t' || c=='\n' ) ...
  274.  
  275. C guarantees that `&&' and `||' are evaluated left to  right
  276. _ we shall soon see cases where this matters.
  277.  
  278.      One of the nice things about C is  that  the  statement
  279. part of an if can be made arbitrarily complicated by enclos-
  280. ing a set of statements in {}.  As a simple example, suppose
  281. we want to ensure that a is bigger than b, as part of a sort
  282. routine.  The interchange of a and b takes three  statements
  283. in C, grouped together by {}:
  284.  
  285.      if (a < b) {
  286.              t = a;
  287.              a = b;
  288.              b = t;
  289.      }
  290.  
  291.  
  292.      As a general rule in C, anywhere you can use  a  simple
  293. statement, you can use any compound statement, which is just
  294. a number of simple or compound ones enclosed in  {}.   There
  295. is  no  semicolon  after  the } of a compound statement, but
  296. there _i_s a semicolon after the last  non-compound  statement
  297. inside the {}.
  298.  
  299.      The ability to replace  single  statements  by  complex
  300. ones  at will is one feature that makes C much more pleasant
  301. to use than Fortran.  Logic (like the exchange in the previ-
  302. ous  example)  which would require several GOTO's and labels
  303. in Fortran can and should be done in C  without  any,  using
  304. compound statements.
  305.  
  306. 7. While Statement; Assignment within  an  Expression; Null
  307. Statement
  308.  
  309.      The basic looping mechanism in C is  the  while  state-
  310. ment.   Here's a program that copies its input to its output
  311. a character at a time.  Remember that `\0' marks the end  of
  312. file.
  313.  
  314.      main( ) {
  315.              char c;
  316.              while( (c=getchar( )) != '\0' )
  317.                      putchar(c);
  318.      }
  319.  
  320. The while statement is a loop, whose general form is
  321.  
  322.      while (expression) statement
  323.  
  324. Its meaning is
  325.  
  326.      (a) evaluate the expression
  327.      (b) if its value is true (i.e., not zero)
  328.                      do the statement, and go back to (a)
  329.  
  330. Because the expression is tested  before  the  statement  is
  331. executed,  the  statement  part  can be executed zero times,
  332. which is often desirable.   As  in  the  if  statement,  the
  333. expression and the statement can both be arbitrarily compli-
  334. cated, although we haven't seen that yet.  Our example  gets
  335. the  character,  assigns  it  to c, and then tests if it's a
  336. `\0''.  If it is not a `\0', the statement part of the while
  337. is   executed,  printing  the  character.   The  while  then
  338. repeats.  When the input character is finally  a  `\0',  the
  339. while terminates, and so does main.
  340.  
  341.      Notice that we used an assignment statement
  342.  
  343.      c = getchar( )
  344.  
  345. within an expression.  This is a handy  notational  shortcut
  346. which often produces clearer code.  (In fact it is often the
  347. only way to write the code cleanly.   As  an  exercise,  re-
  348. write  the  file-copy  without using an assignment inside an
  349. expression.) It works because an assignment statement has  a
  350. value,  just as any other expression does.  Its value is the
  351. value of the right hand side.  This also implies that we can
  352. use multiple assignments like
  353.  
  354.      x = y = z = 0;
  355.  
  356. Evaluation goes from right to left.
  357.  
  358.      By the way, the extra  parentheses  in  the  assignment
  359. statement  within  the conditional were really necessary: if
  360. we had said
  361.  
  362.      c = getchar( ) != '\0'
  363.  
  364. c would be set to 0 or 1 depending on whether the  character
  365. fetched  was  an end of file or not.  This is because in the
  366. absence  of  parentheses  the  assignment  operator  `='  is
  367. evaluated  after  the  relational  operator  `!='.   When in
  368. doubt, or even if not, parenthesize.
  369.  
  370.      Since putchar(c) returns c as its  function  value,  we
  371. could also copy the input to the output by nesting the calls
  372. to getchar and putchar:
  373.  
  374.      main( ) {
  375.              while( putchar(getchar( )) != '\0' ) ;
  376.      }
  377.  
  378. What statement is being repeated?  None, or technically, the
  379. null  statement,  because all the work is really done within
  380. the test part of the while.  This version is  slightly  dif-
  381. ferent  from  the  previous  one,  because the final `\0' is
  382. copied to the output before we decide to stop.
  383.  
  384. 8. Arithmetic
  385.  
  386.      The arithmetic operators are the usual `+',  `-',  `*',
  387. and  `/'  (truncating  integer  division if the operands are
  388. both int), and the remainder or mod operator `%':
  389.  
  390.      x = a%b;
  391.  
  392. sets x to the remainder after a is divided by b (i.e., a mod
  393. b).   The  results  are machine dependent unless a and b are
  394. both positive.
  395.  
  396.      In arithmetic, char variables can  usually  be  treated
  397. like  int  variables.   Arithmetic  on  characters  is quite
  398. legal, and often makes sense:
  399.  
  400.      c = c + 'A' - 'a';
  401.  
  402. converts a single lower case ascii character stored in c  to
  403. upper  case, making use of the fact that corresponding ascii
  404. letters are a fixed distance apart.  The rule governing this
  405. arithmetic is that all chars are converted to int before the
  406. arithmetic is done.   Beware  that  conversion  may  involve
  407. sign-extension  _  if  the leftmost bit of a character is 1,
  408. the resulting integer might be negative.  (This doesn't hap-
  409. pen with genuine characters on any current machine.)
  410.  
  411.      So to convert a file into lower case:
  412.  
  413.      main( ) {
  414.              char c;
  415.              while( (c=getchar( )) != '\0' )
  416.                      if( 'A'<=c && c<='Z' )
  417.                              putchar(c+'a'-'A');
  418.                      else
  419.                              putchar(c);
  420.      }
  421.  
  422. Characters  have  different  sizes  on  different  machines.
  423. Further, this code won't work on an IBM machine, because the
  424. letters in the ebcdic alphabet are not contiguous.
  425.  
  426. 9. Else Clause; Conditional Expressions
  427.  
  428.      We just used an else after an  if.   The  most  general
  429. form of if is
  430.  
  431.      if (expression) statement1 else statement2
  432.  
  433. the else part is optional, but often useful.  The  canonical
  434. example sets x to the minimum of a and b:
  435.  
  436.      if (a < b)
  437.              x = a;
  438.      else
  439.              x = b;
  440.  
  441. Observe that there's a semicolon after x=a.
  442.  
  443.      C provides an alternate form of  conditional  which  is
  444. often  more concise.  It is called the ``conditional expres-
  445. sion'' because it is a  conditional  which  actually  has  a
  446. value and can be used anywhere an expression can.  The value
  447. of
  448.  
  449.      a<b ? a : b;
  450.  
  451. is a if a is less than b; it is b  otherwise.   In  general,
  452. the form
  453.  
  454.      expr1 ? expr2 : expr3
  455.  
  456. means ``evaluate expr1.  If it is not zero, the value of the
  457. whole thing is expr2; otherwise the value is expr3.''
  458.  
  459.      To set x to the minimum of a and b, then:
  460.  
  461.      x = (a<b ? a : b);
  462.  
  463. The parentheses aren't necessary because `?:'  is  evaluated
  464. before `=', but safety first.
  465.  
  466.      Going a step further, we could write the  loop  in  the
  467. lower-case program as
  468.  
  469.      while( (c=getchar( )) != '\0' )
  470.              putchar( ('A'<=c && c<='Z') ? c-'A'+'a' : c );
  471.  
  472.  
  473.      If's and else's can be used  to  construct  logic  that
  474. branches one of several ways and then rejoins, a common pro-
  475. gramming structure, in this way:
  476.  
  477.      if(...)
  478.              {...}
  479.      else if(...)
  480.              {...}
  481.      else if(...)
  482.              {...}
  483.      else
  484.              {...}
  485.  
  486. The conditions are tested in order, and exactly one block is
  487. executed  _  either  the first one whose if is satisfied, or
  488. the one for the last else.  When this block is finished, the
  489. next  statement executed is the one after the last else.  If
  490. no action is to be taken for the ``default'' case, omit  the
  491. last else.
  492.  
  493.      For example, to count letters, digits and others  in  a
  494. file, we could write
  495.  
  496.      main( ) {
  497.              int let, dig, other, c;
  498.              let = dig = other = 0;
  499.              while( (c=getchar( )) != '\0' )
  500.                      if( ('A'<=c && c<='Z') || ('a'<=c && c<='z') )  ++let;
  501.                      else if( '0'<=c && c<='9' )  ++dig;
  502.                      else  ++other;
  503.              printf("%d letters, %d digits, %d others\n", let, dig, other);
  504.      }
  505.  
  506. The `++' operator means ``increment by 1''; we will  get  to
  507. it in the next section.
  508.  
  509. 10. Increment and Decrement Operators
  510.  
  511.      In addition to the usual `-',  C  also  has  two  other
  512. interesting  unary  operators,  `++'  (increment)  and  `--'
  513. (decrement).  Suppose we want to count the lines in a file.
  514.  
  515.      main( ) {
  516.              int c,n;
  517.              n = 0;
  518.              while( (c=getchar( )) != '\0' )
  519.                      if( c == '\n' )
  520.                              ++n;
  521.              printf("%d lines\n", n);
  522.      }
  523.  
  524. ++n is equivalent to n=n+1 but clearer, particularly when  n
  525. is  a  complicated expression.  `++' and `--' can be applied
  526. only to int's and char's (and pointers which we haven't  got
  527. to yet).
  528.  
  529.      The unusual feature of `++' and `--' is that  they  can
  530. be used either before or after a variable.  The value of ++k
  531. is the value of k AFTER it has been incremented.  The  value
  532. of k++ is k BEFORE it is incremented.  Suppose k is 5.  Then
  533.  
  534.      x = ++k;
  535.  
  536. increments k to 6 and then sets x to  the  resulting  value,
  537. i.e., to 6.  But
  538.  
  539.      x = k++;
  540.  
  541. first sets x to to 5, and  THEN  increments  k  to  6.   The
  542. incrementing  effect  of  ++k and k++ is the same, but their
  543. values are respectively 5 and 6.  We shall soon see examples
  544. where both of these uses are important.
  545.  
  546. 11. Arrays
  547.  
  548.      In C, as in Fortran or PL/I, it  is  possible  to  make
  549. arrays  whose elements are basic types.  Thus we can make an
  550. array of 10 integers with the declaration
  551.  
  552.      int x[10];
  553.  
  554. The square brackets mean subscripting; parentheses are  used
  555. only  for function references.  Array indexes begin at zero,
  556. so the elements of x are
  557.  
  558.      x[0], x[1], x[2], ..., x[9]
  559.  
  560. If an array has n elements, the largest subscript is n-1.
  561.  
  562.      Multiple-dimension arrays are provided, though not much
  563. used  above  two  dimensions.   The declaration and use look
  564. like
  565.  
  566.      int name[10] [20];
  567.      n = name[i+j] [1] + name[k] [2];
  568.  
  569. Subscripts can be  arbitrary  integer  expressions.   Multi-
  570. dimension arrays are stored by row (opposite to Fortran), so
  571. the rightmost subscript varies fastest; name has 10 rows and
  572. 20 columns.
  573.  
  574.      Here is a program which reads a line, stores  it  in  a
  575. buffer,  and prints its length (excluding the newline at the
  576. end).
  577.  
  578.      main( ) {
  579.              int n, c;
  580.              char line[100];
  581.              n = 0;
  582.              while( (c=getchar( )) != '\n' ) {
  583.                      if( n < 100 )
  584.                              line[n] = c;
  585.                      n++;
  586.              }
  587.              printf("length = %d\n", n);
  588.      }
  589.  
  590.  
  591.      As a more complicated problem, suppose we want to print
  592. the  count  for  each  line  in the input, still storing the
  593. first 100 characters of each line.  Try it  as  an  exercise
  594. before looking at the solution:
  595.  
  596.      main( ) {
  597.              int n, c; char line[100];
  598.              n = 0;
  599.              while( (c=getchar( )) != '\0' )
  600.                      if( c == '\n' ) {
  601.                              printf("%d0, n);
  602.                              n = 0;
  603.                      }
  604.                      else {
  605.                              if( n < 100 ) line[n] = c;
  606.                              n++;
  607.                      }
  608.      }
  609.  
  610.  
  611. 12. Character Arrays; Strings
  612.  
  613.      Text is usually kept as an array of characters,  as  we
  614. did  with line[ ] in the example above.  By convention in C,
  615. the last character in a character array  should  be  a  `\0'
  616. because  most  programs  that  manipulate  character  arrays
  617. expect it.  For example, printf uses the `\0' to detect  the
  618. end of a character array when printing it out with a `%s'.
  619.  
  620.      We can copy a character array s  into  another  t  like
  621. this:
  622.  
  623.              i = 0;
  624.              while( (t[i]=s[i]) != '\0' )
  625.                      i++;
  626.  
  627.  
  628.      Most of the time we have to put in our own `\0' at  the
  629. end  of  a string; if we want to print the line with printf,
  630. it's necessary.  This code prints the character count before
  631. the line:
  632.  
  633.      main( ) {
  634.              int n;
  635.              char line[100];
  636.              n = 0;
  637.              while( (line[n++]=getchar( )) != '\n' );
  638.              line[n] = '\0';
  639.              printf("%d:\t%s", n, line);
  640.      }
  641.  
  642. Here we increment n in the subscript itself, but only  after
  643. the  previous  value  has been used.  The character is read,
  644. placed in line[n], and only then n is incremented.
  645.  
  646.      There is one place and one place only where C  puts  in
  647. the  `\0'  at the end of a character array for you, and that
  648. is in the construction
  649.  
  650.      "stuff between double quotes"
  651.  
  652. The compiler puts a `\0' at  the  end  automatically.   Text
  653. enclosed in double quotes is called a _s_t_r_i_n_g; its properties
  654. are precisely those of an (initialized) array of characters.
  655.  
  656. 13. For Statement
  657.  
  658.      The for statement is a somewhat generalized while  that
  659. lets us put the initialization and increment parts of a loop
  660. into a single statement along with the  test.   The  general
  661. form of the for is
  662.  
  663.      for( initialization; expression; increment )
  664.              statement
  665.  
  666. The meaning is exactly
  667.  
  668.              initialization;
  669.              while( expression ) {
  670.                      statement
  671.                      increment;
  672.              }
  673.  
  674. Thus, the following code does the same  array  copy  as  the
  675. example in the previous section:
  676.  
  677.              for( i=0; (t[i]=s[i]) != '\0'; i++ );
  678.  
  679. This slightly more ornate example adds up the elements of an
  680. array:
  681.  
  682.              sum = 0;
  683.              for( i=0; i<n; i++)
  684.                      sum = sum + array[i];
  685.  
  686.  
  687.      In the for statement, the initialization  can  be  left
  688. out  if  you  want,  but the semicolon has to be there.  The
  689. increment is also optional.  It is NOT followed by  a  semi-
  690. colon.   The  second clause, the test, works the same way as
  691. in the while: if  the  expression  is  true  (not  zero)  do
  692. another  loop, otherwise get on with the next statement.  As
  693. with the while, the for loop may be done zero times.  If the
  694. expression is left out, it is taken to be always true, so
  695.  
  696.      for( ; ; ) ...
  697.  
  698. and
  699.  
  700.      while( 1 ) ...
  701.  
  702. are both infinite loops.
  703.  
  704.      You might ask why we use a for since it's so much  like
  705. a while.  (You might also ask why we use a while because...)
  706. The for is usually preferable  because  it  keeps  the  code
  707. where  it's  used and sometimes eliminates the need for com-
  708. pound  statements,  as  in  this  code  that  zeros  a  two-
  709. dimensional array:
  710.  
  711.      for( i=0; i<n; i++ )
  712.              for( j=0; j<m; j++ )
  713.                      array[i][j] = 0;
  714.  
  715.  
  716. 14. Functions; Comments
  717.  
  718.      Suppose we want, as part of a larger program, to  count
  719. the  occurrences of the ascii characters in some input text.
  720. Let us also map illegal characters (those with value>127  or
  721. <0)  into  one  pile.   Since this is presumably an isolated
  722. part of the program, good  practice  dictates  making  it  a
  723. separate function.  Here is one way:
  724.  
  725.      main( ) {
  726.              int hist[129];          /* 128 legal chars + 1 illegal group */
  727.              ...
  728.              count(hist, 128);       /* count the letters into hist */
  729.              printf( ... );          /* comments look like this; use them */
  730.              ...             /* anywhere blanks, tabs or newlines could appear */
  731.      }
  732.  
  733.      count(buf, size)
  734.         int size, buf[ ]; {
  735.              int i, c;
  736.              for( i=0; i<=size; i++ )
  737.                      buf[i] = 0;                     /* set buf to zero */
  738.              while( (c=getchar( )) != '\0' ) {       /* read til eof */
  739.                      if( c > size || c < 0 )
  740.                              c = size;               /* fix illegal input */
  741.                      buf[c]++;
  742.              }
  743.              return;
  744.      }
  745.  
  746. We have already seen many examples of calling a function, so
  747. let  us  concentrate  on how to define one.  Since count has
  748. two arguments, we need to declare  them,  as  shown,  giving
  749. their  types, and in the case of buf, the fact that it is an
  750. array.  The declarations of arguments go between  the  argu-
  751. ment  list and the opening `{'.  There is no need to specify
  752. the size of the array buf, for  it  is  defined  outside  of
  753. count.
  754.  
  755.      The return statement simply says to go back to the cal-
  756. ling  routine.   In  fact, we could have omitted it, since a
  757. return is implied at the end of a function.
  758.  
  759.      What if we wanted count to  return  a  value,  say  the
  760. number  of characters read?  The return statement allows for
  761. this too:
  762.  
  763.              int i, c, nchar;
  764.              nchar = 0;
  765.              ...
  766.              while( (c=getchar( )) != '\0' ) {
  767.                      if( c > size || c < 0 )
  768.                              c = size;
  769.                      buf[c]++;
  770.                      nchar++;
  771.              }
  772.              return(nchar);
  773.  
  774. Any expression can appear within the parentheses.  Here is a
  775. function to compute the minimum of two integers:
  776.  
  777.      min(a, b)
  778.         int a, b; {
  779.              return( a < b ? a : b );
  780.      }
  781.  
  782.  
  783.  
  784.      To copy a character array, we could write the function
  785.  
  786.      strcopy(s1, s2)         /* copies s1 to s2 */
  787.         char s1[ ], s2[ ]; {
  788.              int i;
  789.              for( i = 0; (s2[i] = s1[i]) != '\0'; i++ );
  790.      }
  791.  
  792. As is often the case, all the work is done by the assignment
  793. statement  embedded in the test part of the for.  Again, the
  794. declarations of the arguments s1  and  s2  omit  the  sizes,
  795. because  they  don't  matter to strcopy.  (In the section on
  796. pointers, we will see a more efficient way to  do  a  string
  797. copy.)
  798.  
  799.      There is a subtlety in function usage  which  can  trap
  800. the  unsuspecting Fortran programmer.  Simple variables (not
  801. arrays) are passed in C by ``call by  value'',  which  means
  802. that  the  called function is given a copy of its arguments,
  803. and doesn't know their addresses.  This makes it  impossible
  804. to change the value of one of the actual input arguments.
  805.  
  806.      There are two ways out of this dilemma.  One is to make
  807. special  arrangements to pass to the function the address of
  808. a variable instead of its value.  The other is to  make  the
  809. variable  a  global  or external variable, which is known to
  810. each function by its name.  We will discuss both  possibili-
  811. ties in the next few sections.
  812.  
  813. 15. Local and External Variables
  814.  
  815.      If we say
  816.  
  817.      f( ) {
  818.              int x;
  819.              ...
  820.      }
  821.      g( ) {
  822.              int x;
  823.              ...
  824.      }
  825.  
  826. each x is LOCAL to its own routine _ the x in f is unrelated
  827. to   the   x   in  g.   (Local  variables  are  also  called
  828. ``automatic''.) Furthermore each local variable in a routine
  829. appears  only  when  the  function is called, and _d_i_s_a_p_p_e_a_r_s
  830. when the function is exited.  Local variables have no memory
  831. from one call to the next and must be explicitly initialized
  832. upon each entry.  (There is a static storage class for  mak-
  833. ing local variables with memory; we won't discuss it.)
  834.  
  835.      As opposed to local variables, external  variables  are
  836. defined  external  to  all  functions, and are (potentially)
  837. available to all functions.  External storage always remains
  838. in  existence.  To make variables external we have to define
  839. them external to all functions, and, wherever we want to use
  840. them, make a declaration.
  841.  
  842.      main( ) {
  843.              extern int nchar, hist[ ];
  844.              ...
  845.              count( );
  846.              ...
  847.      }
  848.  
  849.      count( ) {
  850.              extern int nchar, hist[ ];
  851.              int i, c;
  852.              ...
  853.      }
  854.  
  855.      int     hist[129];      /* space for histogram */
  856.      int     nchar;          /* character count */
  857.  
  858. Roughly speaking, any function  that  wishes  to  access  an
  859. external variable must contain an extern declaration for it.
  860. The declaration is the same as others, except for the  added
  861. keyword  extern.   Furthermore,  there  must  somewhere be a
  862. definition of the external variables external to  all  func-
  863. tions.
  864.  
  865.      External variables can be initialized; they are set  to
  866. zero  if  not explicitly initialized.  In its simplest form,
  867. initialization is done by putting the value (which must be a
  868. constant) after the definition:
  869.  
  870.      int     nchar   0;
  871.      char    flag    'f';
  872.        etc.
  873.  
  874. This is discussed further in a later section.
  875.  
  876.  
  877.      This ends our discussion of what might  be  called  the
  878. central  core of C.  You now have enough to write quite sub-
  879. stantial C programs, and it would probably be a good idea if
  880. you  paused long enough to do so.  The rest of this tutorial
  881. will describe some more ornate constructions, useful but not
  882. essential.
  883.  
  884. 16. Pointers
  885.  
  886.      A pointer in C is the address of something.   It  is  a
  887. rare  case  indeed  when  we  care what the specific address
  888. itself is, but pointers are a quite common way to get at the
  889. contents  of  something.   The unary operator `&' is used to
  890. produce the address of an object, if it has one. Thus
  891.  
  892.              int a, b;
  893.              b = &a;
  894.  
  895. puts the address of a into b.  We  can't  do  much  with  it
  896. except print it or pass it to some other routine, because we
  897. haven't given b the right kind of declaration.   But  if  we
  898. declare  that  b is indeed a pointer to an integer, we're in
  899. good shape:
  900.  
  901.              int a, *b, c;
  902.              b = &a;
  903.              c = *b;
  904.  
  905. b contains the address of a and `c = *b' means  to  use  the
  906. value in b as an address, i.e., as a pointer.  The effect is
  907. that  we  get  back  the  contents  of  a,   albeit   rather
  908. indirectly.  (It's always the case that `*&x' is the same as
  909. x if x has an address.)
  910.  
  911.      The most frequent use of pointers in C is  for  walking
  912. efficiently along arrays.  In fact, in the implementation of
  913. an array, the array  name  represents  the  address  of  the
  914. zeroth element of the array, so you can't use it on the left
  915. side of an expression.  (You can't  change  the  address  of
  916. something by assigning to it.) If we say
  917.  
  918.      char *y;
  919.      char x[100];
  920.  
  921. y is of type pointer to character (although it  doesn't  yet
  922. point  anywhere).  We can make y point to an element of x by
  923. either of
  924.  
  925.      y = &x[0];
  926.      y = x;
  927.  
  928. Since x is the address of x[0] this is legal and consistent.
  929.  
  930.      Now `*y' gives x[0].  More importantly,
  931.  
  932.      *(y+1)  gives x[1]
  933.      *(y+i)  gives x[i]
  934.  
  935. and the sequence
  936.  
  937.              y = &x[0];
  938.              y++;
  939.  
  940. leaves y pointing at x[1].
  941.  
  942.      Let's use pointers in a function length  that  computes
  943. how  long a character array is.  Remember that by convention
  944. all character arrays are terminated with a  `\0'.   (And  if
  945. they  aren't, this program will blow up inevitably.) The old
  946. way:
  947.  
  948.      length(s)
  949.         char s[ ]; {
  950.              int n;
  951.              for( n=0; s[n] != '\0'; )
  952.                      n++;
  953.              return(n);
  954.      }
  955.  
  956. Rewriting with pointers gives
  957.  
  958.      length(s)
  959.         char *s; {
  960.              int n;
  961.              for( n=0; *s != '\0'; s++ )
  962.                      n++;
  963.              return(n);
  964.      }
  965.  
  966. You can now see why we have to say  what  kind  of  thing  s
  967. points  to  _  if  we're to increment it with s++ we have to
  968. increment it by the right amount.
  969.  
  970.      The pointer version is more efficient (this  is  almost
  971. always true) but even more compact is
  972.  
  973.              for( n=0; *s++ != '\0'; n++ );
  974.  
  975. The `*s'  returns  a  character;  the  `++'  increments  the
  976. pointer  so  we'll  get the next character next time around.
  977. As you can see, as we make things more  efficient,  we  also
  978. make them less clear.  But `*s++' is an idiom so common that
  979. you have to know it.
  980.  
  981.      Going a step further, here's our function strcopy  that
  982. copies a character array s to another t.
  983.  
  984.      strcopy(s,t)
  985.         char *s, *t; {
  986.              while(*t++ = *s++);
  987.      }
  988.  
  989. We have omitted the  test  against  `\0',  because  `\0'  is
  990. identically  zero;  you  will  often  see the code this way.
  991. (You MUST have a space after the `=': see section 25.)
  992.  
  993.      For arguments  to  a  function,  and  there  only,  the
  994. declarations
  995.  
  996.      char s[ ];
  997.      char *s;
  998.  
  999. are equivalent _ a  pointer  to  a  type,  or  an  array  of
  1000. unspecified size of that type, are the same thing.
  1001.  
  1002.      If this all seems mysterious, copy  these  forms  until
  1003. they  become  second  nature.  You don't often need anything
  1004. more complicated.
  1005.  
  1006. 17. Function Arguments
  1007.  
  1008.      Look back at the function strcopy in the previous  sec-
  1009. tion.  We passed it two string names as arguments, then pro-
  1010. ceeded to clobber both of them by  incrementation.   So  how
  1011. come we don't lose the original strings in the function that
  1012. called strcopy?
  1013.  
  1014.      As we said before, C is a ``call by  value''  language:
  1015. when  you  make a function call like f(x), the VALUE of x is
  1016. passed, not its address.  So there's no way to ALTER x  from
  1017. inside  f.  If x is an array (char x[10]) this isn't a prob-
  1018. lem, because x IS an address anyway, and you're  not  trying
  1019. to  change  it, just what it addresses.  This is why strcopy
  1020. works as it does.  And it's convenient not to have to  worry
  1021. about making temporary copies of the input arguments.
  1022.  
  1023.      But what if x is a scalar and you do want to change it?
  1024. In  that  case,  you have to pass the ADDRESS of x to f, and
  1025. then use it as a pointer.  Thus for example, to  interchange
  1026. two integers, we must write
  1027.  
  1028.      flip(x, y)
  1029.         int *x, *y; {
  1030.              int temp;
  1031.              temp = *x;
  1032.              *x = *y;
  1033.              *y = temp;
  1034.      }
  1035.  
  1036. and to call flip, we have to pass the addresses of the vari-
  1037. ables:
  1038.  
  1039.      flip (&a, &b);
  1040.  
  1041.  
  1042. 18. Multiple Levels of Pointers; Program Arguments
  1043.  
  1044.      When a C program is called, the arguments on  the  com-
  1045. mand line are made available to the main program as an argu-
  1046. ment count argc and an array of character strings argv  con-
  1047. taining  the arguments.  Manipulating these arguments is one
  1048. of the most common  uses  of  multiple  levels  of  pointers
  1049. (``pointer  to  pointer  to  ...'').  By convention, argc is
  1050. greater than zero; the first argument (in  argv[0])  is  the
  1051. command name itself.
  1052.  
  1053.      Here is a program that simply echoes its arguments.
  1054.  
  1055.      main(argc, argv)
  1056.         int argc;
  1057.         char **argv; {
  1058.              int i;
  1059.              for( i=1; i < argc; i++ )
  1060.      }
  1061.  
  1062. Step by step: main is called with two arguments,  the  argu-
  1063. ment count and the array of arguments.  argv is a pointer to
  1064. an array, whose individual elements are pointers  to  arrays
  1065. of  characters.  The zeroth argument is the name of the com-
  1066. mand itself, so we start to print with the  first  argument,
  1067. until  we've  printed them all.  Each argv[i] is a character
  1068. array, so we use a `%s' in the printf.
  1069.  
  1070.      You will sometimes see the declaration of argv  written
  1071. as
  1072.  
  1073.      char *argv[ ];
  1074.  
  1075. which is equivalent.  But we can't  use  char  argv[  ][  ],
  1076. because  both  dimensions are variable and there would be no
  1077. way to figure out how big the array is.
  1078.  
  1079.      Here's a bigger example using argc and argv.  A  common
  1080. convention  in  C  programs is that if the first argument is
  1081. `-', it indicates a flag of some sort.  For example, suppose
  1082. we want a program to be callable as
  1083.  
  1084.      prog -abc arg1 arg2 ...
  1085.  
  1086. where the `-' argument is optional; if it is present, it may
  1087. be followed by any combination of a, b, and c.
  1088.  
  1089.      main(argc, argv)
  1090.         int argc;
  1091.         char **argv; {
  1092.              ...
  1093.              aflag = bflag = cflag  = 0;
  1094.              if( argc > 1 && argv[1][0] == '-' ) {
  1095.                      for( i=1; (c=argv[1][i]) != '\0'; i++ )
  1096.                              if( c=='a' )
  1097.                                      aflag++;
  1098.                              else if( c=='b' )
  1099.                                      bflag++;
  1100.                              else if( c=='c' )
  1101.                                      cflag++;
  1102.                              else
  1103.                                      printf("%c?\n", c);
  1104.                      --argc;
  1105.                      ++argv;
  1106.              }
  1107.              ...
  1108.  
  1109.  
  1110.      There are several  things  worth  noticing  about  this
  1111. code.   First,  there  is  a real need for the left-to-right
  1112. evaluation that &&  provides;  we  don't  want  to  look  at
  1113. argv[1] unless we know it's there.  Second, the statements
  1114.  
  1115.              --argc;
  1116.              ++argv;
  1117.  
  1118. let us march along the argument list by one position, so  we
  1119. can skip over the flag argument as if it had never existed _
  1120. the rest of the program is independent  of  whether  or  not
  1121. there  was a flag argument.  This only works because argv is
  1122. a pointer which can be incremented.
  1123.  
  1124. 19. The Switch Statement; Break; Continue
  1125.  
  1126.      The switch statement can be used to replace the  multi-
  1127. way  test  we  used in the last example.  When the tests are
  1128. like this:
  1129.  
  1130.      if( c == 'a' ) ...
  1131.      else if( c == 'b' ) ...
  1132.      else if( c == 'c' ) ...
  1133.      else ...
  1134.  
  1135. testing a value against a series of  constants,  the  switch
  1136. statement  is  often  clearer and usually gives better code.
  1137. Use it like this:
  1138.  
  1139.      switch( c ) {
  1140.  
  1141.      case 'a':
  1142.              aflag++;
  1143.              break;
  1144.      case 'b':
  1145.              bflag++;
  1146.              break;
  1147.      case 'c':
  1148.              cflag++;
  1149.              break;
  1150.      default:
  1151.              printf("%c?\n", c);
  1152.              break;
  1153.      }
  1154.  
  1155. The case statements  label  the  various  actions  we  want;
  1156. default  gets done if none of the other cases are satisfied.
  1157. (A default is optional; if it isn't there, and none  of  the
  1158. cases match, you just fall out the bottom.)
  1159.  
  1160.      The break statement in this  example  is  new.   It  is
  1161. there  because  the  cases are just labels, and after you do
  1162. one of them, you fall through to the next  unless  you  take
  1163. some  explicit  action to escape.  This is a mixed blessing.
  1164. On the positive side, you can have multiple cases on a  sin-
  1165. gle  statement;  we might want to allow both upper and lower
  1166.      case 'a':  case 'A':    ...
  1167.  
  1168.      case 'b':  case 'B':    ...
  1169.       etc.
  1170.  
  1171. But what if we just want to get out after doing case  `a'  ?
  1172. We  could get out of a case of the switch with a label and a
  1173. goto, but this is really ugly.  The break statement lets  us
  1174. exit without either goto or label.
  1175.  
  1176.      switch( c ) {
  1177.  
  1178.      case 'a':
  1179.              aflag++;
  1180.              break;
  1181.      case 'b':
  1182.              bflag++;
  1183.              break;
  1184.       ...
  1185.      }
  1186.      /* the break statements get us here directly */
  1187.  
  1188. The break statement also works in for and while statements _
  1189. it causes an immediate exit from the loop.
  1190.  
  1191.      The continue statement  works  _o_n_l_y  inside  for's  and
  1192. while's;  it  causes  the  next  iteration of the loop to be
  1193. started.  This means it goes to the increment  part  of  the
  1194. for  and  the  test part of the while.  We could have used a
  1195. continue in our example to get on with the next iteration of
  1196. the for, but it seems clearer to use break instead.
  1197.  
  1198. 20. Structures
  1199.  
  1200.      The main use of structures is to lump together  collec-
  1201. tions  of disparate variable types, so they can conveniently
  1202. be treated as a unit.  For example, if  we  were  writing  a
  1203. compiler  or  assembler,  we  might need for each identifier
  1204. information like its name (a character  array),  its  source
  1205. line  number  (an integer), some type information (a charac-
  1206. ter, perhaps), and probably a usage count (another integer).
  1207.  
  1208.              char    id[10];
  1209.              int     line;
  1210.              char    type;
  1211.              int     usage;
  1212.  
  1213.  
  1214.      We can make a structure out of this quite  easily.   We
  1215. first  tell  C  what  the structure will look like, that is,
  1216. what kinds of things it contains; after that we can actually
  1217. reserve  storage  for  it,  either  in the same statement or
  1218. separately.  The simplest thing is to define it and allocate
  1219. storage all at once:
  1220.  
  1221.      struct {
  1222.              char    id[10];
  1223.              int     line;
  1224.              char    type;
  1225.              int     usage;
  1226.      } sym;
  1227.  
  1228.  
  1229.      This defines sym to be a structure with  the  specified
  1230. shape;  id,  line,  type and usage are members of the struc-
  1231. ture.  The way we refer to  any  particular  member  of  the
  1232. structure is
  1233.  
  1234.      structure-name . member
  1235.  
  1236. as in
  1237.  
  1238.              sym.type = 077;
  1239.              if( sym.usage == 0 ) ...
  1240.              while( sym.id[j++] ) ...
  1241.                 etc.
  1242.  
  1243. Although the names of structure members never  stand  alone,
  1244. they  still have to be unique _ there can't be another id or
  1245. usage in some other structure.
  1246.  
  1247.      So far we  haven't  gained  much.   The  advantages  of
  1248. structures  start to come when we have arrays of structures,
  1249. or when we want to pass  complicated  data  layouts  between
  1250. functions.   Suppose we wanted to make a symbol table for up
  1251. to 100 identifiers.  We could extend our definitions like
  1252.  
  1253.              char    id[100][10];
  1254.              int     line[100];
  1255.              char    type[100];
  1256.              int     usage[100];
  1257.  
  1258. but a structure lets us rearrange this  spread-out  informa-
  1259. tion  so  all the data about a single identifer is collected
  1260. into one lump:
  1261.  
  1262.      struct {
  1263.              char    id[10];
  1264.              int     line;
  1265.              char    type;
  1266.              int     usage;
  1267.      } sym[100];
  1268.  
  1269. This makes sym an array of structures;  each  array  element
  1270. has the specified shape.  Now we can refer to members as
  1271.  
  1272.              sym[i].usage++; /* increment usage of i-th identifier */
  1273.              for( j=0; sym[i].id[j++] != '\0'; ) ...
  1274.                 etc.
  1275.  
  1276. Thus to print a list of all identifiers  that  haven't  been
  1277. used, together with their line number,
  1278.  
  1279.              for( i=0; i<nsym; i++ )
  1280.                      if( sym[i].usage == 0 )
  1281.                              printf("%d\t%s\n", sym[i].line, sym[i].id);
  1282.  
  1283.  
  1284.      Suppose we now want to write  a  function  lookup(name)
  1285. which  will tell us if name already exists in sym, by giving
  1286. its index, or that it doesn't, by returning a -1.  We  can't
  1287. pass  a structure to a function directly _ we have to either
  1288. define it externally, or pass a pointer to  it.   Let's  try
  1289. the first way first.
  1290.  
  1291.      int     nsym    0;      /* current length of symbol table */
  1292.  
  1293.      struct {
  1294.              char    id[10];
  1295.              int     line;
  1296.              char    type;
  1297.              int     usage;
  1298.      } sym[100];             /* symbol table */
  1299.  
  1300.      main( ) {
  1301.              ...
  1302.              if( (index = lookup(newname)) >= 0 )
  1303.                      sym[index].usage++;             /* already there ... */
  1304.              else
  1305.                      install(newname, newline, newtype);
  1306.              ...
  1307.      }
  1308.  
  1309.      lookup(s)
  1310.         char *s; {
  1311.              int i;
  1312.              extern struct {
  1313.                      char    id[10];
  1314.                      int     line;
  1315.                      char    type;
  1316.                      int     usage;
  1317.              } sym[ ];
  1318.  
  1319.              for( i=0; i<nsym; i++ )
  1320.                      if( compar(s, sym[i].id) > 0 )
  1321.                              return(i);
  1322.              return(-1);
  1323.      }
  1324.  
  1325.      compar(s1,s2)           /*  return 1 if s1==s2, 0 otherwise */
  1326.         char *s1, *s2; {
  1327.              while( *s1++ == *s2 )
  1328.                      if( *s2++ == '\0' )
  1329.                              return(1);
  1330.              return(0);
  1331.      }
  1332.  
  1333. The declaration of the structure in lookup isn't  needed  if
  1334. the  external definition precedes its use in the same source
  1335. file, as we shall see in a moment.
  1336.  
  1337.      Now what if we want to use pointers?
  1338.  
  1339.      struct  symtag {
  1340.              char    id[10];
  1341.              int     line;
  1342.              char    type;
  1343.              int     usage;
  1344.      } sym[100], *psym;
  1345.  
  1346.              psym = &sym[0]; /* or p = sym; */
  1347.  
  1348. This makes psym a pointer to our kind of structure (the sym-
  1349. bol  table),  then initializes it to point to the first ele-
  1350. ment of sym.
  1351.  
  1352.      Notice that we added something after the word struct: a
  1353. ``tag''  called  symtag.   This puts a name on our structure
  1354. definition so we can refer to it later without repeating the
  1355. definition.   It's  not  necessary  but  useful.  In fact we
  1356. could have said
  1357.  
  1358.      struct  symtag {
  1359.              ... structure definition
  1360.      };
  1361.  
  1362. which wouldn't have assigned any storage at  all,  and  then
  1363. said
  1364.  
  1365.      struct  symtag  sym[100];
  1366.      struct  symtag  *psym;
  1367.  
  1368. which would define the array and the pointer.  This could be
  1369. condensed further, to
  1370.  
  1371.      struct  symtag  sym[100], *psym;
  1372.  
  1373.  
  1374.      The way we actually refer to an member of  a  structure
  1375. by a pointer is like this:
  1376.  
  1377.              ptr -> structure-member
  1378.  
  1379. The symbol `->' means  we're  pointing  at  a  member  of  a
  1380.  
  1381.  
  1382.  
  1383.  
  1384.  
  1385.  
  1386.  
  1387.  
  1388. C Tutorial                 - 27 -
  1389.  
  1390.  
  1391.  
  1392. structure;  `->'  is  only  used  in that context.  ptr is a
  1393. pointer to the (base  of)  a  structure  that  contains  the
  1394. structure   member.   The  expression  ptr->structure-member
  1395. refers to the indicated member of the pointed-to  structure.
  1396. Thus we have constructions like:
  1397.  
  1398.      psym->type = 1;
  1399.      psym->id[0] = 'a';
  1400.  
  1401. and so on.
  1402.  
  1403.      For more complicated pointer expressions, it's wise  to
  1404. use  parentheses  to  make it clear who goes with what.  For
  1405. example,
  1406.  
  1407.      struct { int x, *y; } *p;
  1408.      p->x++  increments x
  1409.      ++p->x  so does this!
  1410.      (++p)->x        increments p before getting x
  1411.      *p->y++ uses y as a pointer, then increments it
  1412.      *(p->y)++       so does this
  1413.      *(p++)->y       uses y as a pointer, then increments p
  1414.  
  1415. The way to remember these is that ->, . (dot), ( ) and  [  ]
  1416. bind  very tightly.  An expression involving one of these is
  1417. treated as a unit.  p->x,  a[i],  y.x  and  f(b)  are  names
  1418. exactly as abc is.
  1419.  
  1420.      If p is a pointer to a structure, any arithmetic  on  p
  1421. takes  into  account  the acutal size of the structure.  For
  1422. instance, p++ increments p by the correct amount to get  the
  1423. next  element  of the array of structures.  But don't assume
  1424. that the size of a structure is the sum of the sizes of  its
  1425. members  _ because of alignments of different sized objects,
  1426. there may be ``holes'' in a structure.
  1427.  
  1428.      Enough theory. Here is the lookup  example,  this  time
  1429. with pointers.
  1430.  
  1431.      struct symtag {
  1432.              char    id[10];
  1433.              int     line;
  1434.              char    type;
  1435.              int     usage;
  1436.      } sym[100];
  1437.  
  1438.      main( ) {
  1439.              struct symtag *lookup( );
  1440.              struct symtag *psym;
  1441.              ...
  1442.              if( (psym = lookup(newname)) )  /* non-zero pointer */
  1443.                      psym -> usage++;                /* means already there */
  1444.              else
  1445.                      install(newname, newline, newtype);
  1446.  
  1447.  
  1448.  
  1449.  
  1450.  
  1451.  
  1452.  
  1453.  
  1454. C Tutorial                 - 28 -
  1455.  
  1456.  
  1457.  
  1458.              ...
  1459.      }
  1460.  
  1461.      struct symtag *lookup(s)
  1462.         char *s; {
  1463.              struct symtag *p;
  1464.              for( p=sym; p < &sym[nsym]; p++ )
  1465.                      if( compar(s, p->id) > 0)
  1466.                              return(p);
  1467.              return(0);
  1468.      }
  1469.  
  1470. The function compar doesn't  change:  `p->id'  refers  to  a
  1471. string.
  1472.  
  1473.      In main we test the pointer returned by lookup  against
  1474. zero,  relying  on  the fact that a pointer is by definition
  1475. never zero when it really points at  something.   The  other
  1476. pointer manipulations are trivial.
  1477.  
  1478.      The only complexity is the set of lines like
  1479.  
  1480.      struct symtag *lookup( );
  1481.  
  1482. This brings us to an area that we will treat only  hurriedly
  1483. _  the question of function types.  So far, all of our func-
  1484. tions have returned integers (or characters, which are  much
  1485. the  same).   What  do we do when the function returns some-
  1486. thing else, like a pointer to a structure?  The rule is that
  1487. any  function  that  doesn't return an int has to say expli-
  1488. citly what it does return.  The type information goes before
  1489. the  function  name  (which  can make the name hard to see).
  1490. Examples:
  1491.  
  1492.      char f(a)
  1493.         int a; {
  1494.              ...
  1495.      }
  1496.  
  1497.      int *g( ) { ... }
  1498.  
  1499.      struct symtag *lookup(s) char *s; { ... }
  1500.  
  1501. The function f returns a character, g returns a  pointer  to
  1502. an integer, and lookup returns a pointer to a structure that
  1503. looks like symtag.  And if we're going to use one  of  these
  1504. functions, we have to make a declaration where we use it, as
  1505. we did in main above.
  1506.  
  1507.      Notice th parallelism between the declarations
  1508.  
  1509.              struct symtag *lookup( );
  1510.              struct symtag *psym;
  1511.  
  1512.  
  1513.  
  1514.  
  1515.  
  1516.  
  1517.  
  1518.  
  1519.  
  1520. C Tutorial                 - 29 -
  1521.  
  1522.  
  1523.  
  1524. In effect, this says that lookup( ) and psym are  both  used
  1525. the  same way _ as a pointer to a strcture _ even though one
  1526. is a variable and the other is a function.
  1527.  
  1528. 21. Initialization of Variables
  1529.  
  1530.      An external variable may be initialized at compile time
  1531. by  following its name with an initializing value when it is
  1532. defined.  The initializing value has to be  something  whose
  1533. value is known at compile time, like a constant.
  1534.  
  1535.      int     x       0;      /* "0" could be any constant */
  1536.      int     a       'a';
  1537.      char    flag    0177;
  1538.      int     *p      &y[1];  /* p now points to y[1] */
  1539.  
  1540. An external array can be initialized by following  its  name
  1541. with a list of initializations enclosed in braces:
  1542.  
  1543.      int     x[4]    {0,1,2,3};              /* makes x[i] = i */
  1544.      int     y[ ]    {0,1,2,3};              /* makes y big enough for 4 values */
  1545.      char    *msg    "syntax error\n";       /* braces unnecessary here */
  1546.      char *keyword[ ]{
  1547.              "if",
  1548.              "else",
  1549.              "for",
  1550.              "while",
  1551.              "break",
  1552.              "continue",
  1553.              0
  1554.      };
  1555.  
  1556. This last one is very useful _ it makes keyword an array  of
  1557. pointers  to character strings, with a zero at the end so we
  1558. can identify the last element easily.  A simple lookup  rou-
  1559. tine  could  scan  this  until  it  either  finds a match or
  1560. encounters a zero keyword pointer:
  1561.  
  1562.      lookup(str)             /* search for str in keyword[ ] */
  1563.         char *str; {
  1564.              int i,j,r;
  1565.              for( i=0; keyword[i] != 0; i++) {
  1566.                      for( j=0; (r=keyword[i][j]) == str[j] && r != '\0'; j++ );
  1567.                      if( r == str[j] )
  1568.                              return(i);
  1569.              }
  1570.              return(-1);
  1571.      }
  1572.  
  1573.  
  1574.      Sorry _ neither local variables nor structures  can  be
  1575. initialized.
  1576.  
  1577. 22. Scope Rules: Who Knows About What
  1578.  
  1579.      A complete C program need not be compiled all at  once;
  1580. the source text of the program may be kept in several files,
  1581. and  previously  compiled  routines  may  be   loaded   from
  1582. libraries.  How do we arrange that data gets passed from one
  1583. routine to another?  We have already seen how to  use  func-
  1584. tion  arguments  and  values,  so let us talk about external
  1585. data.  Warning: the words  declaration  and  definition  are
  1586. used precisely in this section; don't treat them as the same
  1587. thing.
  1588.  
  1589.      A major shortcut exists for making extern declarations.
  1590. If  the  definition  of a variable appears BEFORE its use in
  1591. some function, no extern declaration is  needed  within  the
  1592. function.  Thus, if a file contains
  1593.  
  1594.      f1( ) { ... }
  1595.  
  1596.      int foo;
  1597.  
  1598.      f2( ) { ... foo = 1; ... }
  1599.  
  1600.      f3( ) { ... if ( foo ) ... }
  1601.  
  1602. no declaration of foo is needed  in  either  f2  or  or  f3,
  1603. because  the external definition of foo appears before them.
  1604. But if f1 wants to use foo, it has to contain  the  declara-
  1605. tion
  1606.  
  1607.      f1( ) {
  1608.              extern int foo;
  1609.              ...
  1610.      }
  1611.  
  1612.  
  1613.      This is true  also  of  any  function  that  exists  on
  1614. another  file  _  if  it  wants  foo it has to use an extern
  1615. declaration for  it.   (If  somewhere  there  is  an  extern
  1616. declaration  for something, there must also eventually be an
  1617. external definition of it, or you'll get an ``undefined sym-
  1618. bol'' message.)
  1619.  
  1620.      There are some hidden pitfalls in external declarations
  1621. and  definitions if you use multiple source files.  To avoid
  1622. them, first, define and initialize  each  external  variable
  1623. only once in the entire set of files:
  1624.  
  1625.      int     foo     0;
  1626.  
  1627. You can get away with multiple external definitions on UNIX,
  1628. but  not  on  GCOS, so don't ask for trouble.  Multiple ini-
  1629. tializations are illegal everywhere.  Second, at the  begin-
  1630. ning  of any file that contains functions needing a variable
  1631. whose definition is in some other file,  put  in  an  extern
  1632. declaration, outside of any function:
  1633.  
  1634.      extern  int     foo;
  1635.  
  1636.      f1( ) { ... }
  1637.         etc.
  1638.  
  1639.  
  1640.      The #include compiler control  line,  to  be  discussed
  1641. shortly,  lets  you  make  a  single  copy  of  the external
  1642. declarations for a program and then stick them into each  of
  1643. the source files making up the program.
  1644.  
  1645. 23. #define, #include
  1646.  
  1647.      C provides a very limited macro facility.  You can say
  1648.  
  1649.      #define name            something
  1650.  
  1651. and thereafter anywhere ``name'' appears as a token, ``some-
  1652. thing'' will be substituted.  This is particularly useful in
  1653. parametering the sizes of arrays:
  1654.  
  1655.      #define ARRAYSIZE       100
  1656.              int     arr[ARRAYSIZE];
  1657.               ...
  1658.              while( i++ < ARRAYSIZE )...
  1659.  
  1660. (now we can alter the entire program by  changing  only  the
  1661. define) or in setting up mysterious constants:
  1662.  
  1663.      #define SET             01
  1664.      #define INTERRUPT       02      /* interrupt bit */
  1665.      #define ENABLED 04
  1666.       ...
  1667.      if( x & (SET | INTERRUPT | ENABLED) ) ...
  1668.  
  1669. Now we have meaningful  words  instead  of  mysterious  con-
  1670. stants.   (The  mysterious  operators `&' (AND) and `|' (OR)
  1671. will be covered in the  next  section.)  It's  an  excellent
  1672. practice  to  write  programs  without any literal constants
  1673. except in #define statements.
  1674.  
  1675.      There  are  several  warnings  about  #define.   First,
  1676. there's  no  semicolon at the end of a #define; all the text
  1677. from the name to the end of the line (except  for  comments)
  1678. is  taken  to  be the ``something''.  When it's put into the
  1679. text, blanks are placed around  it.   Good  style  typically
  1680. makes the name in the #define upper case _ this makes param-
  1681. eters more visible.  Definitions affect  things  only  after
  1682. they  occur,  and  only within the file in which they occur.
  1683. Defines can't be nested.  Last, if there is a #define  in  a
  1684. file, then the first character of the file MUST be a `#', to
  1685. signal the preprocessor that definitions exist.
  1686.  
  1687.  
  1688.      The other control word known  to  C  is  #include.   To
  1689. include one file in your source at compilation time, say
  1690.  
  1691.      #include "filename"
  1692.  
  1693. This is useful for putting a lot of heavily used data defin-
  1694. itions  and #define statements at the beginning of a file to
  1695. be compiled.  As with #define, the first line of a file con-
  1696. taining  a  #include  has to begin with a `#'.  And #include
  1697. can't be nested _ an included  file  can't  contain  another
  1698. #include.
  1699.  
  1700. 24. Bit Operators
  1701.  
  1702.      C has several  operators  for  logical  bit-operations.
  1703. For example,
  1704.  
  1705.      x = x & 0177;
  1706.  
  1707. forms the bit-wise AND of x and 0177, effectively  retaining
  1708. only the last seven bits of x.  Other operators are
  1709.  
  1710.      |       inclusive OR
  1711.      ^       (circumflex) exclusive OR
  1712.      ~       (tilde) 1's complement
  1713.      !       logical NOT
  1714.      <<      left shift (as in x<<2)
  1715.      >>      right shift     (arithmetic on PDP-11; logical on H6070, IBM360)
  1716.  
  1717.  
  1718. 25. Assignment Operators
  1719.  
  1720.      An unusual feature of  C  is  that  the  normal  binary
  1721. operators  like  `+',  `-',  etc.   can be combined with the
  1722. assignment operator `=' to form  new  assignment  operators.
  1723. For example,
  1724.  
  1725.      x =- 10;
  1726.  
  1727. uses the assignment operator `=-' to decrement x by 10, and
  1728.  
  1729.      x =& 0177
  1730.  
  1731. forms the AND of x and 0177.  This convention  is  a  useful
  1732. notational  shortcut,  particularly  if  x  is a complicated
  1733. expression.  The classic example is summing an array:
  1734.  
  1735.      for( sum=i=0; i<n; i++ )
  1736.              sum =+ array[i];
  1737.  
  1738. But the  spaces  around  the  operator  are  critical!   For
  1739.      x = -10;
  1740.  
  1741. sets x to -10, while
  1742.  
  1743.      x =- 10;
  1744.  
  1745. subtracts 10 from x.  When no space is present,
  1746.  
  1747.      x=-10;
  1748.  
  1749. also decreases x by 10.   This  is  quite  contrary  to  the
  1750. experience  of  most  programmers.  In particular, watch out
  1751. for things like
  1752.  
  1753.      c=*s++;
  1754.      y=&x[0];
  1755.  
  1756. both of which are almost  certainly  not  what  you  wanted.
  1757. Newer  versions of various compilers are courteous enough to
  1758. warn you about the ambiguity.
  1759.  
  1760.      Because  all  other  operators  in  an  expression  are
  1761. evaluated  before  the  assignment  operator,  the  order of
  1762. evaluation should be watched carefully:
  1763.  
  1764.      x = x<<y | z;
  1765.  
  1766. means ``shift x left y places, then OR with z, and store  in
  1767. x.'' But
  1768.  
  1769.      x =<< y | z;
  1770.  
  1771. means ``shift x left by y|z places'', which is  rather  dif-
  1772. ferent.
  1773.  
  1774. 26. Floating Point
  1775.  
  1776.      We've skipped over  floating  point  so  far,  and  the
  1777. treatment  here will be hasty.  C has single and double pre-
  1778. cision numbers (where the precision depends on  the  machine
  1779. at hand).  For example,
  1780.  
  1781.              double sum;
  1782.              float avg, y[10];
  1783.              sum = 0.0;
  1784.              for( i=0; i<n; i++ )
  1785.                      sum =+ y[i];
  1786.              avg = sum/n;
  1787.  
  1788. forms the sum and average of the array y.
  1789.  
  1790.      All floating arithmetic is done  in  double  precision.
  1791. Mixed mode arithmetic is legal; if an arithmetic operator in
  1792. an expression has both operands int or char, the  arithmetic
  1793. done  is  integer, but if one operand is int or char and the
  1794. other is float or double, both  operands  are  converted  to
  1795. double.  Thus if i and j are int and x is float,
  1796.  
  1797.      (x+i)/j         converts i and j to float
  1798.      x + i/j         does i/j integer, then converts
  1799.  
  1800. Type conversion may be made by assignment; for instance,
  1801.  
  1802.              int m, n;
  1803.              float x, y;
  1804.              m = x;
  1805.              y = n;
  1806.  
  1807. converts x to integer (truncating toward  zero),  and  n  to
  1808. floating point.
  1809.  
  1810.      Floating constants are just like those  in  Fortran  or
  1811. PL/I, except that the exponent letter is `e' instead of `E'.
  1812. Thus:
  1813.  
  1814.              pi = 3.14159;
  1815.              large = 1.23456789e10;
  1816.  
  1817.      printf will format floating point numbers: ``%w.df'' in
  1818. the format string will print the corresponding variable in a
  1819. field w digits wide, with d decimal places.  An e instead of
  1820. an f will produce exponential notation.
  1821.  
  1822. 27. Horrors! goto's and labels
  1823.  
  1824.      C has a goto statement and labels, so  you  can  branch
  1825. about  the  way  you  used  to.  But most of the time goto's
  1826. aren't needed.  (How many have we used up  to  this  point?)
  1827. The  code  can  almost  always  be more clearly expressed by
  1828. for/while, if/else, and compound statements.
  1829.  
  1830.      One use of goto's with some legitimacy is in a  program
  1831. which  contains  a  long loop, where a while(1) would be too
  1832. extended.  Then you might write
  1833.  
  1834.         mainloop:
  1835.              ...
  1836.              goto mainloop;
  1837.  
  1838. Another use is to implement a break out  of  more  than  one
  1839. level  of  for  or  while.  goto's can only branch to labels
  1840. within the same function.
  1841.  
  1842. 28. Acknowledgements
  1843.  
  1844.      I am indebted to a veritable host of readers  who  made
  1845. valuable  criticisms  on  several  drafts  of this tutorial.
  1846. They ranged in experience from  complete  beginners  through
  1847. several  implementors  of  C  compilers  to  the  C language
  1848. designer himself.  Needless to say, this is  a  wide  enough
  1849. spectrum of opinion that no one is satisfied (including me);
  1850. comments and suggestions are still  welcome,  so  that  some
  1851. future version might be improved.
  1852.  
  1853. References
  1854.  
  1855.      C is an extension of B, which was  designed  by  D.  M.
  1856. Ritchie  and  K. L. Thompson [4].  The C language design and
  1857. UNIX implementation are the work of D. M. Ritchie.  The GCOS
  1858. version  was  begun  by A. Snyder and B. A. Barres, and com-
  1859. pleted by S. C. Johnson and M. E. Lesk.  The IBM version  is
  1860. primarily  due  to T. G. Peterson, with the assistance of M.
  1861. E. Lesk.
  1862.  
  1863. [1]   D. M. Ritchie, C Reference Manual.   Bell  Labs,  Jan.
  1864.       1974.
  1865.  
  1866. [2]   M. E. Lesk & B. A. Barres, The  GCOS  C  Library.
  1867.           Bell Labs, Jan. 1974.
  1868.  
  1869. [3]   D.  M.   Ritchie   &   K.   Thompson,  UNIX Programmer's
  1870.       Manual.  5th Edition, Bell Labs, 1974.
  1871.  
  1872. [4]   S. C. Johnson & B.  W.  Kernighan,  The Programming
  1873.       Language  B.  Computer Science  Technical  Report  8,
  1874.       Bell  Labs, 1972.
  1875.  
  1876. End.
  1877.